<template>
  <div class="marketing-activity">
    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="活动名称">
          <el-input v-model="searchForm.name" placeholder="请输入活动名称" clearable />
        </el-form-item>
        <el-form-item label="活动类型">
          <el-select v-model="searchForm.type" placeholder="请选择" clearable>
            <el-option label="限时促销" value="promotion" />
            <el-option label="满减活动" value="discount" />
            <el-option label="新人礼包" value="newbie" />
            <el-option label="节日活动" value="festival" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="未开始" value="pending" />
            <el-option label="进行中" value="active" />
            <el-option label="已结束" value="ended" />
            <el-option label="已暂停" value="paused" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleCreate">新建活动</el-button>
    </div>

    <!-- 活动列表 -->
    <el-card class="table-card">
      <el-table v-loading="loading" :data="tableData" border stripe>
        <el-table-column prop="name" label="活动名称" min-width="150" />
        <el-table-column prop="type" label="活动类型" width="100">
          <template #default="{ row }">
            <el-tag>{{ getTypeText(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="活动描述" min-width="200" />
        <el-table-column prop="startTime" label="开始时间" width="160" />
        <el-table-column prop="endTime" label="结束时间" width="160" />
        <el-table-column prop="participantCount" label="参与人数" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="text" size="small" @click="handleViewData(row)">数据</el-button>
            <el-button 
              type="text" 
              size="small" 
              @click="handleToggleStatus(row)"
              :style="{ color: row.status === 'paused' ? '#67C23A' : '#F56C6C' }"
            >
              {{ row.status === 'paused' ? '恢复' : '暂停' }}
            </el-button>
            <el-popconfirm title="确定删除该活动吗？" @confirm="handleDelete(row)">
              <template #reference>
                <el-button type="text" size="small" style="color: #f56c6c;">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="loadTableData"
          @size-change="loadTableData"
        />
      </div>
    </el-card>

    <!-- 活动表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '新建活动' : '编辑活动'"
      width="800px"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动类型" prop="type">
          <el-select v-model="formData.type" style="width: 100%;">
            <el-option label="限时促销" value="promotion" />
            <el-option label="满减活动" value="discount" />
            <el-option label="新人礼包" value="newbie" />
            <el-option label="节日活动" value="festival" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input v-model="formData.description" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="活动时间" prop="timeRange">
          <el-date-picker
            v-model="formData.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="活动规则">
          <el-input v-model="formData.rules" type="textarea" :rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getActivityList, createActivity, updateActivity, deleteActivity } from '@/api/marketing'

export default {
  name: 'MarketingActivity',
  setup() {
    const loading = ref(false)
    const submitLoading = ref(false)
    const dialogVisible = ref(false)
    const dialogType = ref('create')
    const formRef = ref()

    const searchForm = reactive({
      name: '',
      type: '',
      status: ''
    })

    const pagination = reactive({
      current: 1,
      size: 20,
      total: 0
    })

    const tableData = ref([])

    const formData = reactive({
      id: '',
      name: '',
      type: '',
      description: '',
      timeRange: [],
      rules: ''
    })

    const formRules = {
      name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
      type: [{ required: true, message: '请选择活动类型', trigger: 'change' }],
      description: [{ required: true, message: '请输入活动描述', trigger: 'blur' }],
      timeRange: [{ required: true, message: '请选择活动时间', trigger: 'change' }]
    }

    const typeMap = {
      promotion: '限时促销',
      discount: '满减活动', 
      newbie: '新人礼包',
      festival: '节日活动'
    }

    const statusMap = {
      pending: { text: '未开始', type: 'info' },
      active: { text: '进行中', type: 'success' },
      ended: { text: '已结束', type: 'info' },
      paused: { text: '已暂停', type: 'warning' }
    }

    const getTypeText = (type) => typeMap[type] || type
    const getStatusText = (status) => statusMap[status]?.text || status
    const getStatusType = (status) => statusMap[status]?.type || 'default'

    const loadTableData = async () => {
      loading.value = true
      try {
        const res = await getActivityList({
          page: pagination.current,
          size: pagination.size,
          ...searchForm
        })
        
        if (res && (res.code === 200 || res.data || res.content)) {
          const data = res.data || res
          tableData.value = data.content || data.records || data || []
          pagination.total = data.totalElements || data.total || 0
        } else {
          tableData.value = []
          pagination.total = 0
        }
      } catch (error) {
        console.error('获取活动列表失败:', error)
        ElMessage.warning('获取活动列表失败，请检查网络连接')
        tableData.value = []
        pagination.total = 0
      } finally {
        loading.value = false
      }
    }

    const handleSearch = () => {
      pagination.current = 1
      loadTableData()
    }

    const handleReset = () => {
      Object.assign(searchForm, { name: '', type: '', status: '' })
      handleSearch()
    }

    const handleCreate = () => {
      dialogType.value = 'create'
      resetFormData()
      dialogVisible.value = true
    }

    const handleEdit = (row) => {
      dialogType.value = 'edit'
      Object.assign(formData, {
        ...row,
        timeRange: [row.startTime, row.endTime]
      })
      dialogVisible.value = true
    }

    const handleDelete = async (row) => {
      try {
        await deleteActivity(row.id)
        ElMessage.success('删除成功')
        loadTableData()
      } catch (error) {
        ElMessage.error('删除失败')
      }
    }

    const handleViewData = (row) => {
      ElMessage.info('查看活动数据功能')
    }

    const handleToggleStatus = async (row) => {
      try {
        const newStatus = row.status === 'paused' ? 'active' : 'paused'
        await updateActivity(row.id, { status: newStatus })
        ElMessage.success(`${newStatus === 'active' ? '恢复' : '暂停'}成功`)
        loadTableData()
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }

    const handleSubmit = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
        submitLoading.value = true
        
        const submitData = {
          ...formData,
          startTime: formData.timeRange[0],
          endTime: formData.timeRange[1]
        }
        delete submitData.timeRange
        
        let res
        if (dialogType.value === 'create') {
          res = await createActivity(submitData)
        } else {
          res = await updateActivity(formData.id, submitData)
        }
        
        if (res && (res.code === 200 || res.success)) {
          ElMessage.success(dialogType.value === 'create' ? '创建成功' : '更新成功')
          dialogVisible.value = false
          loadTableData()
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      } finally {
        submitLoading.value = false
      }
    }

    const resetFormData = () => {
      Object.assign(formData, {
        id: '',
        name: '',
        type: '',
        description: '',
        timeRange: [],
        rules: ''
      })
    }

    onMounted(() => {
      loadTableData()
    })

    return {
      loading,
      submitLoading,
      dialogVisible,
      dialogType,
      formRef,
      searchForm,
      pagination,
      tableData,
      formData,
      formRules,
      getTypeText,
      getStatusText,
      getStatusType,
      loadTableData,
      handleSearch,
      handleReset,
      handleCreate,
      handleEdit,
      handleDelete,
      handleViewData,
      handleToggleStatus,
      handleSubmit
    }
  }
}
</script>

<style scoped>
.marketing-activity {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 